package com.zhang.security;

import com.zhang.common.exception.CaptchaException;
import com.zhang.common.lang.Const;
import com.zhang.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//验证码过滤器
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String url = request.getRequestURI();

        if("/login".equals(url) && request.getMethod().equals("POST")){
            //校验验证码是否正确
            try{
                validate(request);
            }catch (CaptchaException e){
                //不正确则交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        //校验成功往后面走
        filterChain.doFilter(request,response);
    }

    //验证验证码是否正确
    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("key");

        if(StringUtils.isBlank(code)||StringUtils.isBlank(key)){
            throw new CaptchaException("验证码错误");
        }
        if(!code.equals(redisUtil.hget(Const.Captcha_Key,key))){
            throw new CaptchaException("验证码错误");
        }

//        //一次性使用，使用完删除         已转移到登陆成功处理器删除
//        redisUtil.hdel(Const.Captcha_Key,key);
    }
}
